package tcm.com.gistone.controller;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import tcm.com.gistone.database.config.GetBySqlMapper;
import tcm.com.gistone.database.entity.Bookinfo;
import tcm.com.gistone.database.entity.Knowledge;
import tcm.com.gistone.database.entity.WarmKnowledge;
import tcm.com.gistone.database.mapper.BookinfoMapper;
import tcm.com.gistone.database.mapper.KnowledgeMapper;
import tcm.com.gistone.database.mapper.WarmKnowledgeMapper;
import tcm.com.gistone.util.ClientUtil;
import tcm.com.gistone.util.EdatResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:renqiang
 * @Param:
 * @Description:专家知识管理
 * @Date:14:48 2017/8/9
 */

@RestController
@RequestMapping( "knowledge" )
@Transactional
public class KnowledgeController {

    @Autowired
    private KnowledgeMapper km;
    @Autowired
    private GetBySqlMapper gm;
    @Autowired
    private BookinfoMapper bm;
    @Autowired
    private WarmKnowledgeMapper wkm;

    /*删除专家知识*/
    @RequestMapping( value = "deleteKnowledge", method = RequestMethod.POST )
    @Transactional( rollbackFor = Exception.class )
    public EdatResult deleteKnowkedge(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            JSONArray jsonArray = data.getJSONArray("ids");
            for (int i = 0; i < jsonArray.size(); i++) {
                long id = jsonArray.getLong(i);
                km.deleteByPrimaryKey(id);
            }
            return EdatResult.build(0, "success");
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("{\"status\":\"1\",\"msg\":\"删除失败\",\"data\":\"\"}");
            throw e;
        }
    }

    /*修改专家知识*/
    @RequestMapping( value = "updateKnowledge", method = RequestMethod.POST )
    @Transactional( rollbackFor = Exception.class )
    public EdatResult updataKnowledge(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            long id = data.getLong("id");
            Knowledge knowledge = km.selectByPrimaryKey(id);
            knowledge.setAlias(data.getString("alias"));
            knowledge.setKnowledgeType(data.getString("knowledge_type"));
            knowledge.setBirthEnv(data.getString("birth_env"));
            knowledge.setPart(data.getString("part"));
            knowledge.setTaste(data.getString("taste"));
            knowledge.setGas(data.getString("gas"));
            knowledge.setChannelTropism(data.getString("channel_tropism"));
            knowledge.setLift(data.getString("lift"));
            knowledge.setToxicity(data.getString("toxicity"));
            knowledge.setBeard(data.getString("beard"));
            knowledge.setMake(data.getString("make"));
            knowledge.setHate(data.getString("hate"));
            knowledge.setMurder(data.getString("murder"));
            knowledge.setFear(data.getString("fear"));
            knowledge.setAgainst(data.getString("against"));
            knowledge.setMainFunction(data.getString("main_function"));
            knowledge.setSymptom(data.getString("symptom"));
            knowledge.setDisease(data.getString("disease"));
            knowledge.setComponent(data.getString("component"));
            knowledge.setUsages(data.getString("usages"));
            knowledge.setProcessing(data.getString("processing"));
            knowledge.setHarvest(data.getString("harvest"));
            knowledge.setGenuine(data.getString("genuine"));
            knowledge.setIdentification(data.getString("identification"));
            knowledge.setUseLevel(data.getString("use_level"));
            knowledge.setRecording(data.getString("recording"));
            knowledge.setOther(data.getString("other"));
            knowledge.setTaboo(data.getString("taboo"));
            knowledge.setSideEffect(data.getString("side_effect"));
            knowledge.setDrugLike(data.getString("drug_like"));
            knowledge.setAttention(data.getString("attention"));
            knowledge.setFigure(data.getString("figure"));
            km.updateByPrimaryKey(knowledge);
            return EdatResult.build(0, "success");
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("{\"status\":\"1\",\"msg\":\"更新失败\",\"data\":\"\"}");
            throw e;
        }

    }

    /*录入专家知识*/
    @RequestMapping( value = "recordKnowledge", method = RequestMethod.POST )
    @Transactional( rollbackFor = Exception.class )
    public EdatResult getBookinfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            long specialId = data.getLong("specialId");
            String bookName = data.getString("bookName");/*书籍名称*/
            Bookinfo bookinfo = bm.selectOne(specialId, bookName);
            if (null == bookinfo) {
                return EdatResult.build(1, "文献不存在");
            }
            long bookId = bookinfo.getBookId();
            String name = data.getString("word");/*专家知识名称，排重*/
            String sql = "select * from tb_knowledge where book_id = " + bookId + " and knowledge_name = '" + name + "'";
            List<Map> list = gm.findRecords(sql);
            if (list.size() > 0) {
                return EdatResult.build(1, "名称重复");
            }
            Knowledge knowledge = new Knowledge();
            knowledge.setSpecialId(specialId);
            knowledge.setKnowledgeName(name);
            knowledge.setBookId(bookId);
            knowledge.setAlias(data.getString("alias"));
            knowledge.setKnowledgeType(data.getString("knowledge_type"));
            knowledge.setBirthEnv(data.getString("birth_env"));
            knowledge.setPart(data.getString("part"));
            knowledge.setTaste(data.getString("taste"));
            knowledge.setGas(data.getString("gas"));
            knowledge.setChannelTropism(data.getString("channel_tropism"));
            knowledge.setLift(data.getString("lift"));
            knowledge.setToxicity(data.getString("toxicity"));
            knowledge.setBeard(data.getString("beard"));
            knowledge.setMake(data.getString("make"));
            knowledge.setHate(data.getString("hate"));
            knowledge.setMurder(data.getString("murder"));
            knowledge.setFear(data.getString("fear"));
            knowledge.setAgainst(data.getString("against"));
            knowledge.setMainFunction(data.getString("main_function"));
            knowledge.setSymptom(data.getString("symptom"));
            knowledge.setDisease(data.getString("disease"));
            knowledge.setComponent(data.getString("component"));
            knowledge.setUsages(data.getString("usages"));
            knowledge.setProcessing(data.getString("processing"));
            knowledge.setHarvest(data.getString("harvest"));
            knowledge.setGenuine(data.getString("genuine"));
            knowledge.setIdentification(data.getString("identification"));
            knowledge.setUseLevel(data.getString("use_level"));
            knowledge.setRecording(data.getString("recording"));
            knowledge.setOther(data.getString("other"));
            knowledge.setTaboo(data.getString("taboo"));
            knowledge.setSideEffect(data.getString("side_effect"));
            knowledge.setDrugLike(data.getString("drug_like"));
            knowledge.setAttention(data.getString("attention"));
            knowledge.setFigure(data.getString("figure"));
            km.insert(knowledge);
            return EdatResult.build(0, "success");
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("{\"status\":\"1\",\"msg\":\"删除失败\",\"data\":\"\"}");
            throw e;
        }
    }

    /*根据名称模糊查询所有主题词*/
    @RequestMapping( value = "selectAllKnowledge", method = RequestMethod.POST )
    public Map selectAllKnowledge(HttpServletRequest request, HttpServletResponse response) {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            int pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
            int pageSize = Integer.parseInt(request.getParameter("pageSize"));
            String keyWord = request.getParameter("keyWord");/*关键词*/
            long specialId = Long.parseLong(request.getParameter("specialId"));
            List<Map> list = new ArrayList<>();
            int total = 0;
            if (specialId == 1) {/*本草专题*/
                String sql2 = "";
                if (!keyWord.equals("")) {
                    sql2 = " and ( a.knowledge_name like '%" + keyWord + "%'or a.alias like '%" + keyWord + "%')";
                }
                String sql = "select a.*,b.book_name from tb_knowledge a  join tb_bookinfo b on a.book_id =b.book_id where 1=1 " + sql2 + " order by knowledge_type, knowledge_name limit " + pageNumber + "," + pageSize;
                String sql1 = "select count(*) from tb_knowledge a  join tb_bookinfo b on a.book_id = b.book_id where 1=1 " + sql2;
                list = gm.findRecords(sql);
                total = gm.findrows(sql1);
            } else if (specialId == 3) {/*温病专题*/
                String sql2 = "";
                if (!keyWord.equals("")) {
                    sql2 = "and word like '%" + keyWord + "%'  or alias like '%" + keyWord + "%'";
                }
                String sql = "select * from tb_warm_knowledge  where 1=1 " + sql2 + " order by type,word  limit " + pageNumber + "," + pageSize;
                String sql1 = "select count(*) from tb_warm_knowledge where  1=1 " + sql2;
                list = gm.findRecords(sql);
                total = gm.findrows(sql1);
            }
            Map map = new HashMap();
            map.put("rows", list);
            map.put("total", total);
            map.put("page", pageNumber / pageSize);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * @Author:renqiang
     * @Param:
     * @Description:添加温病专题知识提取
     * @Date:10:29 2017/12/5
     */
    @RequestMapping( value = "addWarnKnowledge", method = RequestMethod.POST )
    public EdatResult addWarnKnowledge(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            String type = data.getString("type");//类型
            String name = data.getString("name");//一级名称
            String name1 = data.getString("fir_name");//二级名称
            String name2 = data.getString("sec_name");//二级名称
            String alias = data.getString("alias");//同义词
            String cause = data.getString("cause");//病因病机
            String symptoms = data.getString("symptoms");//症状体征
            String syndorme = data.getString("syndorme");//证候
            String method = data.getString("method");//治法
            String prescription = data.getString("prescription");//方剂
            String medical = data.getString("medical");//中药
            String book = data.getString("book");//医籍
            String person = data.getString("person");//医家
            WarmKnowledge warmKnowledge = new WarmKnowledge();
            warmKnowledge.setType(type);
            warmKnowledge.setWord(name);
            warmKnowledge.setSecDisease(name2);
            warmKnowledge.setAlias(alias);
            warmKnowledge.setDisease(name1);
            warmKnowledge.setCausePathogenesis(cause);
            warmKnowledge.setSymptoms(symptoms);
            warmKnowledge.setSyndrome(syndorme);
            warmKnowledge.setCureMethod(method);
            warmKnowledge.setPrescription(prescription);
            warmKnowledge.setChineseMedicine(medical);
            warmKnowledge.setMedicalBook(book);
            warmKnowledge.setMedicalPerson(person);
            wkm.insert(warmKnowledge);
            return EdatResult.build(0, "success");
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("{\"status\":\"1\",\"msg\":\"添加失败\",\"data\":\"\"}");
            throw e;
        }
    }

    /**
     * @Author:renqiang
     * @Param:
     * @Description:修改温病知识提取
     * @Date:10:56 2017/12/5
     */
    @RequestMapping( value = "modifyWarnKnowledge", method = RequestMethod.POST )
    public EdatResult modifyWarnKnowledge(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            long id = data.getLong("id");
            String type = data.getString("type");//类型
            String name = data.getString("name");//名称
            String name1 = data.getString("fir_name");//一级病名
            String name2 = data.getString("sec_name");//二级病名
            String alias = data.getString("alias");//同义词
            String cause = data.getString("cause");//病因病机
            String symptoms = data.getString("symptoms");//症状体征
            String syndorme = data.getString("syndorme");//证候
            String method = data.getString("method");//治法
            String prescription = data.getString("prescription");//方剂
            String medical = data.getString("medical");//中药
            String book = data.getString("book");//医籍
            String person = data.getString("person");//医家
            WarmKnowledge warmKnowledge = new WarmKnowledge();
            warmKnowledge.setId(id);
            warmKnowledge.setType(type);
            warmKnowledge.setWord(name);
            warmKnowledge.setSecDisease(name2);
            warmKnowledge.setAlias(alias);
            warmKnowledge.setDisease(name1);
            warmKnowledge.setCausePathogenesis(cause);
            warmKnowledge.setSymptoms(symptoms);
            warmKnowledge.setSyndrome(syndorme);
            warmKnowledge.setCureMethod(method);
            warmKnowledge.setPrescription(prescription);
            warmKnowledge.setChineseMedicine(medical);
            warmKnowledge.setMedicalBook(book);
            warmKnowledge.setMedicalPerson(person);
            wkm.updateByPrimaryKey(warmKnowledge);
            return EdatResult.build(0, "success");
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("{\"status\":\"1\",\"msg\":\"修改失败\",\"data\":\"\"}");
            throw e;
        }
    }

    /**
     * @Author:renqiang
     * @Param:
     * @Description:删除温病专题知识提取
     * @Date:10:30 2017/12/5
     */
    @RequestMapping( value = "deleteWarmKnowledge", method = RequestMethod.POST )
    public EdatResult deleteWarmKnowledge(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            JSONArray jsonArray = data.getJSONArray("ids");
            for (int i = 0; i < jsonArray.size(); i++) {
                long id = jsonArray.getLong(i);
                wkm.deleteByPrimaryKey(id);
            }
            return EdatResult.build(0, "success");
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("{\"status\":\"1\",\"msg\":\"删除失败\",\"data\":\"\"}");
            throw e;
        }
    }

    /**
     * @Author:renqiang
     * @Param:
     * @Description:获取温病专题知识提取详情
     * @Date:10:30 2017/12/5
     */
    @RequestMapping( value = "getAWarnKnowledge", method = RequestMethod.POST )
    public EdatResult getAWarnKnowledge(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            Long id = data.getLong("id");
            WarmKnowledge warmKnowledge = wkm.selectByPrimaryKey(id);
            return EdatResult.ok(warmKnowledge);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("{\"status\":\"1\",\"msg\":\"删除失败\",\"data\":\"\"}");
            throw e;
        }
    }
}
